package com.cn.algorithm01;

/**
 * @author hels
 * @version 1.0
 * @date 2021/10/13 16:58
 * 在任意数据队列中，k个为一组进行逆序排列
 * 测试链接：https://leetcode.com/problems/reverse-nodes-in-k-group/
 */
public class Code10_ReverseNodesInGroup {

    // 单链表结构
    public static class ListNode {
        public int val;
        public ListNode next;
    }

    // 核心算法
    public static ListNode reverseKGroup(ListNode head, int k) {
        ListNode start = head;
        ListNode end = getKGroupEnd(start, k);
        if (end == null) {
            return head;
        }

        // 第一组数据够了
        head = end;
        reverse(start, end);
        // 上一组结尾的节点
        ListNode lastEnd = start;

        //对后续数据进行循环实现
        while (lastEnd.next != null) {
            start = lastEnd.next;
            end = getKGroupEnd(start, k);
            if (end == null) {
                return head;
            }

            reverse(start, end);
            lastEnd.next = end;
            lastEnd = start;
        }

        return head;
    }

    // 获取分组内最后一个节点
    public static ListNode getKGroupEnd(ListNode start, int k) {
        while (--k != 0 && start != null) {
            start = start.next;
        }
        return start;
    }
    // 分组内进行反序排列
    public static void reverse(ListNode start, ListNode end) {
        ListNode pre = null;
        ListNode cur = start;
        ListNode next = null;
        end = end.next;
        while (cur != end) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        start.next = end;
    }


}
